package com.mogician.feihualing.feihualing;

import android.content.Context;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class PoemUtil
{

    public static ArrayList<Poem> parseAndFilter(Context context, String filename, String key)
    {
        BufferedReader br = null;
        try
        {
            ArrayList<Poem> poemList = new ArrayList<>();
            br = new BufferedReader(new InputStreamReader(
                                context.getResources().getAssets().open(filename), "utf-8"));
            poemList.clear();

            int count = 0;
            int id = -1;
            String title = "", poet = "";
            Poem p = null;
            String text;
            while((text = br.readLine()) != null)
            {
                count++;
                if(text.isEmpty())
                {
                    //是序，而且之前加入了该诗（id一样）
                    if(count == 4 && p != null && p.getId() == id)
                    {
                        poemList.remove(p);
                    }
                    continue;
                }

                if(text.substring(0,3).matches("^[0-9]{3}"))
                {
                    count = 0;
                    int pos = text.indexOf("：");
                    id = Integer.parseInt(text.substring(0, 3));
                    poet = text.substring(3, pos);
                    title = text.substring(pos + 1);
                }
                else
                {
                    if(text.contains(key))
                    {
                        p = new Poem(id, title, poet, text);
                        poemList.add(p);
                    }
                }
            }
            return poemList;
        } catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
        finally
        {
            try
            {
                br.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}
